use colored::*;
use std::fs;
use std::path::Path;
use std::process::Command;

/// 检查大文件（超过指定MB的文件）
pub fn check_large_files(max_size_mb: u64) -> bool {
    println!("{}", "🔍 检查大文件...".yellow());
    
    let max_bytes = max_size_mb * 1024 * 1024;
    
    // 获取暂存的文件列表
    let output = Command::new("git")
        .args(["diff", "--cached", "--name-only"])
        .output()
        .expect("执行git命令失败");
    
    let files = String::from_utf8_lossy(&output.stdout);
    let mut large_files = Vec::new();
    
    for file in files.lines() {
        if let Ok(metadata) = fs::metadata(file) {
            if metadata.len() > max_bytes {
                large_files.push((file.to_string(), metadata.len()));
            }
        }
    }
    
    if !large_files.is_empty() {
        eprintln!("{}", "❌ 检测到大文件:".red());
        for (file, size) in large_files {
            let size_mb = size as f64 / 1024.0 / 1024.0;
            eprintln!("  {} ({:.2} MB)", file, size_mb);
        }
        eprintln!();
        eprintln!("{}", "💡 建议:".yellow());
        eprintln!("  1. 使用Git LFS管理大文件");
        eprintln!("  2. 将大文件添加到.gitignore");
        eprintln!("  3. 压缩文件或移除不必要的资源");
        return false;
    }
    
    println!("{}", "✅ 文件大小检查通过".green());
    true
}

/// 检查禁止提交的文件
pub fn check_forbidden_files() -> bool {
    println!("{}", "🔍 检查禁止提交的文件...".yellow());
    
    let forbidden_patterns = vec![
        "build/",
        ".dart_tool/",
        "ios/Pods/",
        ".idea/",
        "*.iml",
        ".DS_Store",
        "node_modules/",
        ".vscode/",
    ];
    
    let output = Command::new("git")
        .args(["diff", "--cached", "--name-only"])
        .output()
        .expect("执行git命令失败");
    
    let files = String::from_utf8_lossy(&output.stdout);
    let mut found_forbidden = false;
    
    for pattern in &forbidden_patterns {
        let matching_files: Vec<&str> = files
            .lines()
            .filter(|f| {
                if pattern.contains('*') {
                    // 简单的通配符匹配
                    let ext = pattern.trim_start_matches('*');
                    f.ends_with(ext)
                } else {
                    f.contains(pattern)
                }
            })
            .collect();
        
        if !matching_files.is_empty() {
            if !found_forbidden {
                eprintln!("{}", "❌ 检测到禁止提交的文件:".red());
                found_forbidden = true;
            }
            eprintln!("  模式 {}: ", pattern.cyan());
            for file in matching_files {
                eprintln!("    - {}", file);
            }
        }
    }
    
    if found_forbidden {
        eprintln!();
        eprintln!("{}", "💡 建议:".yellow());
        eprintln!("  1. 检查并更新.gitignore配置");
        eprintln!("  2. 使用 git reset HEAD <file> 取消暂存");
        eprintln!("  3. 删除或移动这些文件到正确位置");
        return false;
    }
    
    println!("{}", "✅ 禁止文件检查通过".green());
    true
}

/// 检测是否是Flutter项目
pub fn is_flutter_project() -> bool {
    Path::new("pubspec.yaml").exists()
}

/// 检测是否是Unity项目
pub fn is_unity_project() -> bool {
    Path::new("Assets").exists() && Path::new("ProjectSettings").exists()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_is_flutter_project() {
        // 这个测试依赖于实际文件系统
        // 在实际项目中可能需要mock
        let result = is_flutter_project();
        assert!(result == Path::new("pubspec.yaml").exists());
    }

    #[test]
    fn test_is_unity_project() {
        let result = is_unity_project();
        assert!(result == (Path::new("Assets").exists() && Path::new("ProjectSettings").exists()));
    }
}